//SPDX-FileCopyrightText: Copyright 2025-2025 深圳市同心圆网络有限公司
//SPDX-License-Identifier: GPL-3.0-only

use tauri::{App, AppHandle, Manager, Runtime};
use tokio::fs;
use tokio::io::AsyncReadExt;
use tokio::io::AsyncWriteExt;
use tokio::sync::RwLock;

#[derive(Default)]
pub struct FileLock(pub RwLock<i32>);

#[derive(serde::Serialize, serde::Deserialize, Clone, PartialEq)]
pub struct ServerInfo {
    pub name: String,
    pub system: bool,
    pub addr: String,
    pub default_server: bool,
}

#[derive(serde::Serialize, serde::Deserialize, Clone, PartialEq)]
pub struct ListServerResult {
    pub server_list: Vec<ServerInfo>,
}

#[tauri::command]
pub async fn client_cfg_list_server<R: Runtime>(app_handle: AppHandle<R>) -> ListServerResult {
    let _l = app_handle.state::<FileLock>().inner().0.read().await;

    let mut result = ListServerResult {
        server_list: Vec::new(),
    };
    result.server_list.push(ServerInfo {
        name: "官方".into(),
        system: true,
        addr: "serv.eteam.chat:5010".into(),
        default_server: false,
    });

    //读取配置文件
    if let Some(cfg_path) = get_server_cfg().await {
        if let Ok(mut f) = fs::File::open(cfg_path).await {
            let mut data: Vec<u8> = Vec::new();
            if let Ok(_) = f.read_to_end(&mut data).await {
                if let Ok(json_str) = String::from_utf8(data) {
                    let server_list: Result<Vec<ServerInfo>, serde_json::Error> =
                        serde_json::from_str(&json_str);
                    if server_list.is_ok() {
                        for info in server_list.unwrap() {
                            result.server_list.push(info);
                        }
                    }
                }
            }
        }
    }
    let mut has_default = false;
    for info in &(result.server_list) {
        if info.default_server {
            has_default = true;
        }
    }
    if !has_default {
        result.server_list[0].default_server = true;
    }

    return result;
}

#[tauri::command]
pub async fn client_cfg_save_server_list<R: Runtime>(
    app_handle: AppHandle<R>,
    server_list: Vec<ServerInfo>,
) {
    let _l = app_handle.state::<FileLock>().inner().0.write().await;

    let mut new_server_list: Vec<ServerInfo> = Vec::new();

    for info in &server_list {
        if info.system {
            continue;
        }
        new_server_list.push(ServerInfo {
            name: info.name.clone(),
            system: false,
            addr: info.addr.clone(),
            default_server: info.default_server,
        });
    }

    if let Ok(json_str) = serde_json::to_string(&new_server_list) {
        if let Some(cfg_path) = get_server_cfg().await {
            if let Ok(mut f) = fs::File::create(cfg_path).await {
                if let Err(err) = f.write_all(json_str.as_bytes()).await {
                    println!("{}", err);
                }
            }
        }
    }
}

async fn get_server_cfg() -> Option<String> {
    if let Some(base_dir) = crate::get_base_dir() {
        return Some(format!("{}/server.json", base_dir));
    }
    None
}

pub fn init(app: &App) {
    app.manage(FileLock(Default::default()));
}
